package com.aidong.util;

import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

import java.io.IOException;
import java.util.Map;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;

public class QiniuMP4Util {
	//设置好账号的ACCESS_KEY和SECRET_KEY  
    String ACCESS_KEY = "SOMBFhoOmUgnKcmLYPoYlZxUa4E7E5sJp7nW5YDU"; //这两个登录七牛 账号里面可以找到  
    String SECRET_KEY = "be2JUix4G-CayPHwXa6Wz4TD9E13Ffjc6QQH9qzn";  

    //要上传的空间  
    //String bucketname = "adong"; //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）
  //上传文件的路径
  String FilePath = "D:\\mp4.mp4";

  //设置转码操作参数
  //String fops = "avthumb/mp4/s/640x360/vb/1.25m";
  
  String fops="avthumb/m3u8/segtime/10/vb/5m/vcodec/libx264/acodec/libfaac/s/1330x750";
  
  //String fops="avthumb/mp4;avthumb/m3u8/noDomain/1/segtime/15/vb/440k";
  
  String entryURI = "test:123467.m3u8";
  //设置转码的队列
  String pipeline = "qiniu0629";
  //上传到七牛后保存的文件名  
  String key = System.currentTimeMillis()+FilePath.substring(FilePath.lastIndexOf("."));    
  //可以对转码后的文件进行使用saveas参数自定义命名，当然也可以不指定文件会默认命名并保存在当前空间。
  String urlbase64 = UrlSafeBase64.encodeToString(entryURI);
  String pfops = fops + "|saveas/" + urlbase64;
  
  //密钥配置
  Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
  //创建上传对象
  UploadManager uploadManager = new UploadManager();

  //上传策略中设置persistentOps字段和persistentPipeline字段
  public String getUpToken(){
      return auth.uploadToken(QiniuUtil.BUCKET_NAME,null,3600,new StringMap()
          .putNotEmpty("persistentOps", pfops)
          .putNotEmpty("persistentPipeline", pipeline), true);
  }

  public void upload() throws IOException{
    try {
    	System.out.println(urlbase64);
      //调用put方法上传
      Response res = uploadManager.put(FilePath, key, getUpToken());
      //打印返回的信息
      System.out.println(res.bodyString()); 
      StringMap msp=res.jsonToMap();
      System.out.println(msp.get("key"));
      } catch (QiniuException e) {
          Response r = e.response;
          // 请求失败时打印的异常的信息
          System.out.println(r.toString());
          try {
              //响应的文本信息
            System.out.println(r.bodyString());
          } catch (QiniuException e1) {
              //ignore
          }
      }       
  }

  public static void main(String args[]) throws IOException{  
    new QiniuMP4Util().upload();
    
  }

}